import java.io.*;
import java.util.Scanner;


/**
 * Created with IntelliJ IDEA.
 * Description:
 */
public class Demo3 {
    public static void main(String[] args) {
        System.out.println("请输入要查询的目录");
        Scanner scanner = new Scanner(System.in);
        String pathRoot = scanner.next();
        File fileRoot = new File(pathRoot);
        if (!fileRoot.isDirectory()) {
            System.out.println("输入的路径不是目录");
        } else {
            System.out.println("请输入要查找的关键字");
            String keyword = scanner.next();
            scanDir(fileRoot, keyword);

        }
    }

    private static void scanDir(File fileRoot, String keyword)  {
        File[] files = fileRoot.listFiles();
        if (files == null) {
            return;
        }
        //用来存放文件内容
        StringBuilder st = new StringBuilder();
        //遍历目录
        for (File file : files) {
            if (file.isFile()) {
                //判断文件名是否包含关键字
                if (file.getName().contains(keyword)) {
                    System.out.println("文件名包含关键字："+file.getAbsolutePath());
                }else {
                    //读取文件内容，判断是否包含关键字
                    try(InputStream inputStream = new FileInputStream(file)) {
                        while (true){
                            byte[] bytes = new byte[1024];
                            int ch = inputStream.read(bytes);
                            if (ch == -1) {
                                break;
                            }
                            st.append(new String(bytes));
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    if(st.indexOf(keyword)!=-1){
                        System.out.println("文件内容包含关键字："+file.getAbsolutePath());
                    }
                }
            } else {
                scanDir(file, keyword);
            }
        }
    }
}
